package org.example.currency;

import cn.hutool.core.date.StopWatch;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @Title : ThreadTest
 * @Description:
 * @author: libo@juzishuke.com
 * @date: 2023/12/20 20:02
 * @Version:1.0
 */
public class ThreadTest {

    public static void main(String[] args) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("t1");
        ExecutorService executor = Executors.newFixedThreadPool(5);
        List<Future<Integer>> futureList = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(999);
        for (int i = 1; i < 1000; i++) {
            int finalI = i;
            futureList.add(executor.submit(() -> {
                try {
                    Thread.sleep(100);
                    if (finalI % 10 == 0) {
                        //                        throw new Exception("test" + finalI);
                    }
                    return finalI;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                    return finalI;

                }
            }));
        }
        stopWatch.stop();
        System.out.println("submit end " + stopWatch.getTotalTimeMillis());
        stopWatch.start("t2");
        latch.await();
        stopWatch.stop();
        System.out.println("sync end " + stopWatch.getTotalTimeMillis());
        stopWatch.start("t3");
        for (Future<Integer> f : futureList) {
            try {
                System.out.print(f.get());
            } catch (Exception e) {
                System.err.println(e);
                executor.shutdown();
            }
        }
        stopWatch.stop();
        System.out.println("end "+ stopWatch.getTotalTimeMillis());
        System.out.println(stopWatch.prettyPrint(TimeUnit.MILLISECONDS));
    }

}
